/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {
    AppRegistry,
    TouchableHighlight,
    TouchableNativeFeedback,
    ListView,
    InteractionManager,
    Image,
    View,
    StyleSheet,
    Text,
    ToastAndroid,
    TouchableWithoutFeedback,
    ToolbarAndroid,
    ActivityIndicator,
    RefreshControl,
    Navigator,
    BackAndroid,
    Platform
} from 'react-native';
import CustomToolbar from './app/widgets/CustomToolbar';
import ListViewFooter from './app/widgets/ListViewFooter';
import GameDetail from './GameDetail';

let pageNum = 1;
let totalList = [];

class DefaultImage extends Component {

    state = {
        error: false,
    };

    render() {
        if (!this.state.error) {
            return (
                <Image
                    onError={() => this.setState({error: true})}
                    style={this.props.style}
                    source={this.props.source}/>
            );
        } else {
            return (
                <Image
                    style={this.props.style}
                    source={require('./img/icon_base_map.png')}/>
            );
        }
    }
}

class App extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        let name = 'AwesomeProject';
        let home = AwesomeProject;
        return (
            <Navigator
                initialRoute={{ name: name, component: home }}
                configureScene={(route, routeStack) => Navigator.SceneConfigs.FadeAndroid}
                renderScene={(route, navigator) => {
                let Component = route.component;
                return <Component {...route.params} navigator={navigator} />
                }} />
        );
    }
}

class AwesomeProject extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            firstLoad: true,
            foot: 0, //0 正在加载 1 全部加载完成 2 加载失败
            isLoadMore: false,
            isRefresh: false
        };
    }

    render() {
        if (this.state.firstLoad) {
            return (
                <Text>Loading</Text>
            );
        }
        return (
            <View style={{flex: 1}}>
                <CustomToolbar title='游戏列表' showLeftIcon={false}/>

                <ListView
                    enableEmptySections={true}
                    style={{flex: 1}}
                    dataSource={this.state.dataSource}
                    renderRow={this._renderRow.bind(this)}
                    initialListSize={20}
                    renderFooter={this._renderFooter.bind(this)}
                    renderSeparator={this._renderSeperator.bind(this)}
                    onEndReachedThreshold={10}
                    onEndReached={this._endReached.bind(this)}
                    refreshControl={
                        <RefreshControl
                          refreshing={this.state.isRefresh}
                          onRefresh={this._onRefresh.bind(this)}
                          colors={['#ff0000', '#00ff00', '#0000ff','#3ad564']}
                          progressBackgroundColor="#ffffff"/>
                    }
                />
            </View>

        );
    }

    _endReached() {
        if (!this.state.isLoadMore) {
            pageNum++;
            this.setState({isLoadMore: true});
            this._fetchData();
        }
    }

    _onRefresh() {
        this.setState({isRefresh: true});
        let URL = `http://api.17168.com/?cmd=81000&data={"page":1}`;
        let p = Promise.race([
            fetch(URL),
            new Promise(function (resolve, reject) {
                setTimeout(() => reject(new Error('request timeout')), 5000)
            })
        ]);
        p.then(response => {
            return response.json()
        })
            .then(responseData => {
                pageNum = 1;
                console.log(responseData);
                let list = responseData.data.recommend_data.game_list;
                totalList = [];
                if (list.length === 20) {
                    list.forEach((item) => totalList.push(item));
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(totalList),
                        firstLoad: false,
                        foot: 0,
                        isLoadMore: false,
                        isRefresh: false
                    });
                } else if (list.length < 20) {
                    this.setState({
                        foot: 1,
                        isLoadMore: false,
                        isRefresh: false
                    });
                }
            }).catch((error) => {
            this.setState({
                isRefresh: false
            });
        }).done();
    }

    _renderSeperator(sectionID: number, rowID: number, adjacentRowHighlighted: bool) {
        return (
            <View
                key={`${sectionID}-${rowID}`}
                style={styles.listItemSeperator}/>
        );
    }

    _fetchData() {
        let URL = `http://api.17168.com/?cmd=81000&data={"page":${pageNum}}`;
        console.log(URL);
        let p = Promise.race([
            fetch(URL),
            new Promise(function (resolve, reject) {
                setTimeout(() => reject(new Error('request timeout')), 5000)
            })
        ]);
        p.then(response => {
            return response.json()
        })
            .then(responseData => {
                console.log(responseData);
                let list = responseData.data.recommend_data.game_list;
                if (list.length === 20) {
                    list.forEach((item) => totalList.push(item));
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(totalList),
                        firstLoad: false,
                        foot: 0,
                        isLoadMore: false
                    });
                } else if (list.length < 20) {
                    this.setState({
                        foot: 1,
                        isLoadMore: false
                    });
                }
            }).catch((error) => {
            pageNum--;
            this.setState({
                foot: 2,
                isLoadMore: false
            });
        }).done();
    }

    componentWillMount() {
        InteractionManager.runAfterInteractions(() => this._fetchData());
    }

    componentWillUnmount() {
        if (Platform.OS === 'ios') {

        } else {
            BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid.bind(this));
        }
    }

    componentDidMount() {
        if (Platform.OS === 'ios') {

        } else {
            BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid.bind(this));
        }
    }

    onBackAndroid() {
        const {navigator} = this.props;
        const routers = navigator.getCurrentRoutes();
        if (routers.length > 1) {
            navigator.pop();
            return true;
        }
        return false;
    };

    _renderRow(rowData, sectionID, rowID, highlightRow) {
        return (
            this._renderType(rowData, sectionID, rowID, highlightRow)
        );
    }

    _calcSize(size) {
        return `${(size / 1024 / 1024).toFixed(2)} M`;
    }

    _onItemClick(rowData,rowID){
        const { navigator } = this.props;
        if(navigator) {
            navigator.push({
                name: 'GameDetail',
                component: GameDetail,
                params:{
                    rowData
                }
            })
        }
    }

    _renderType(rowData, sectionID, rowID, highlightRow) {
        if (!rowData.icon) {
            return (
                <TouchableWithoutFeedback
                    onPress={() => ToastAndroid.show(`This is ${+rowID + 1} row!`, ToastAndroid.SHORT)}>
                    <View>
                        <DefaultImage source={{uri: rowData.photo_url}} style={styles.listItemSpecialImage}/>
                    </View>
                </TouchableWithoutFeedback>
            );
        } else {
            return (
                <TouchableNativeFeedback
                    onPress={() => {
                        this._onItemClick(rowData, rowID);
                    }}>
                    <View style={styles.listItem}>
                        <DefaultImage source={{uri: rowData.icon}}
                                      style={styles.listItemGameIcon}/>
                        <View style={styles.listItemDescContainer}>
                            <Text numberOfLines={1} style={styles.listItemGameName}>{rowData.name}</Text>
                            <View style={styles.listItemGameLabelContainer}>
                                {this._renderLabel(rowData)}
                            </View>
                            <Text numberOfLines={1} ellipsizeMode='tail'
                                  style={styles.listItemGameDesc}>{rowData.description}</Text>
                        </View>
                        <View style={styles.listItemRightContainer}>
                            <TouchableHighlight underlayColor='#fef2e9'
                                                style={styles.listItemRightButton}
                                                onPress={() => ToastAndroid.show(`click ${+rowID + 1} download!`, ToastAndroid.SHORT)}>
                                <Text style={styles.listItemRightButtonText}>下载</Text>
                            </TouchableHighlight>
                            <Text style={styles.listItemRightSize}>{this._calcSize(rowData.game_size)}</Text>
                        </View>
                    </View>
                </TouchableNativeFeedback>
            );
        }
    }

    _renderLabel(rowData) {
        if (rowData.keyword) {
            return rowData.keyword.map((value, index) => {
                if (index > 2) {
                    return null;
                }
                return (
                    <Text key={index}
                          style={[styles.listItemGameLabel, {backgroundColor: labelColor[index]}]}>{value}</Text>
                );
            });
        }
    }

    _renderFooter() {
        if (this.state.foot === 0) {
            return (
                <ListViewFooter footState={0}/>
            );
        } else if (this.state.foot === 1) {
            return (
                <ListViewFooter footState={1}/>
            );
        } else if (this.state.foot === 2) {
            return (
                <TouchableHighlight underlayColor='transparent'
                                    onPress={() => this._endReached()}>
                    <View>
                        <ListViewFooter footState={2}/>
                    </View>
                </TouchableHighlight>
            );
        }
    }

}

const labelColor = ['#91a7ff', '#ffab91', '#4fc3f7'];

const styles = StyleSheet.create({
    toolbar: {
        backgroundColor: '#f67d29',
        height: 49,
    },
    listItem: {
        height: 85,
        backgroundColor: 'white',
        flexDirection: 'row',
        paddingLeft: 15,
        paddingRight: 15,
        justifyContent: 'space-around',
        // borderBottomWidth: StyleSheet.hairlineWidth,
        // borderBottomColor: '#e1e1e1'
    },
    listItemSeperator: {
        height: StyleSheet.hairlineWidth,
        backgroundColor: '#e1e1e1',
        marginHorizontal: 15
    },
    listItemDescContainer: {
        flex: 1,
        marginLeft: 10,
        flexDirection: 'column',
        marginTop: 8
    },
    listItemGameName: {
        color: '#1e1e1e',
        fontSize: 18,
    },
    listItemGameDesc: {
        color: '#767675',
        fontSize: 12,
        marginTop: 5,
    },
    listItemGameLabelContainer: {
        flexDirection: 'row',
        marginTop: 5
    },
    listItemGameLabel: {
        borderRadius: 3,
        fontSize: 10,
        color: 'white',
        marginRight: 8,
        paddingLeft: 3,
        paddingRight: 3
    },
    listItemRightContainer: {
        height: 85,
        flexDirection: 'column',
        alignItems: 'center'
    },
    listItemRightButton: {
        borderRadius: 5,
        borderColor: '#f67d29',
        borderWidth: 1,
        backgroundColor: 'white',
        marginTop: 29,
        width: 55,
        height: 27
    },
    listItemRightButtonText: {
        flex: 1,
        color: '#f67d29',
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 14,
    },
    listItemRightSize: {
        color: '#767675',
        fontSize: 10,
        marginTop: 5
    },
    listItemGameIcon: {
        width: 55,
        height: 55,
        borderRadius: 10,
        alignSelf: 'center'
    },
    listItemSpecialImage: {
        height: 150,
        marginVertical: 9
    },
    listViewFooterContainer: {
        height: 40,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
});

// 注意，这里用引号括起来的'AwesomeProject'必须和你init创建的项目名一致
AppRegistry.registerComponent('AwesomeProject', () => App);